import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'statistics_page.dart';
import 'special_statistics_page.dart';
import 'count_page.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '今日任务',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: const TodoListScreen(),
    );
  }
}

class TodoListScreen extends StatefulWidget {
  const TodoListScreen({super.key});

  @override
  State<TodoListScreen> createState() => _TodoListScreenState();
}

class _TodoListScreenState extends State<TodoListScreen> {
  final Map<String, List<bool>> _dailyTasks = {};
  DateTime _selectedDate = DateTime.now();
  final List<String> _taskTitles = [
    '护肤',
    '吃药',
    '深蹲',
    '跳绳',
    '挥拍',
    '单词',
    '历史',
    '编程',
    '收拾',
    '静坐',
  ];

  @override
  void initState() {
    super.initState();
    _loadTasks();
  }

  Future<void> _loadTasks() async {
    final prefs = await SharedPreferences.getInstance();
    final String? tasksJson = prefs.getString('tasks');
    if (tasksJson != null) {
      final Map<String, dynamic> decoded = json.decode(tasksJson);
      setState(() {
        decoded.forEach((key, value) {
          _dailyTasks[key] = List<bool>.from(value);
        });
      });
    }
    _initDayTasks(_selectedDate);
  }

  Future<void> _saveTasks() async {
    final prefs = await SharedPreferences.getInstance();
    final String tasksJson = json.encode(_dailyTasks);
    await prefs.setString('tasks', tasksJson);
  }

  void _initDayTasks(DateTime date) {
    final dateKey = _dateToString(date);
    if (!_dailyTasks.containsKey(dateKey)) {
      _dailyTasks[dateKey] = List.generate(_taskTitles.length, (index) => false);
    }
  }

  List<bool> _getTasksForDate(String dateKey) {
    if (!_dailyTasks.containsKey(dateKey)) {
      _dailyTasks[dateKey] = List.generate(_taskTitles.length, (index) => false);
    }
    return _dailyTasks[dateKey]!;
  }

  String _dateToString(DateTime date) {
    return '${date.year}-${date.month}-${date.day}';
  }

  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }

  @override
  Widget build(BuildContext context) {
    final dateKey = _dateToString(_selectedDate);
    final tasks = _getTasksForDate(dateKey);
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('每日任务'),
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        actions: [
          IconButton(
            icon: const Icon(Icons.directions_run),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const CountPage(),
                ),
              );
            },
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _taskTitles.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(
                    _taskTitles[index],
                    style: TextStyle(
                      decoration: tasks[index]
                          ? TextDecoration.lineThrough
                          : TextDecoration.none,
                      color: tasks[index]
                          ? Colors.grey[400]
                          : Colors.black,
                    ),
                  ),
                  trailing: Checkbox(
                    value: tasks[index],
                    onChanged: (bool? value) {
                      setState(() {
                        tasks[index] = value ?? false;
                        _saveTasks();
                      });
                    },
                  ),
                );
              },
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // 向左箭头
                Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: () {
                      setState(() {
                        _selectedDate = _selectedDate.subtract(const Duration(days: 1));
                        _initDayTasks(_selectedDate);
                      });
                    },
                    child: Container(
                      padding: const EdgeInsets.all(12.0),
                      child: const Icon(
                        Icons.chevron_left,
                        size: 40,
                        color: Colors.blue,
                      ),
                    ),
                  ),
                ),
                // 日期显示
                GestureDetector(
                  onTap: () {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return Dialog(
                          child: CalendarDatePicker(
                            initialDate: _selectedDate,
                            firstDate: DateTime(2025, 1, 1),
                            lastDate: DateTime(2025, 12, 31),
                            onDateChanged: (DateTime value) {
                              setState(() {
                                _selectedDate = value;
                                _initDayTasks(value);
                              });
                              Navigator.pop(context);
                            },
                          ),
                        );
                      },
                    );
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0),
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.blue),
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                    child: Text(
                      _isSameDay(_selectedDate, DateTime(
                        DateTime.now().year,
                        DateTime.now().month,
                        DateTime.now().day,
                      ))
                          ? '今天'
                          : '${_selectedDate.year}年${_selectedDate.month}月${_selectedDate.day}日',
                      style: const TextStyle(fontSize: 18),
                    ),
                  ),
                ),
                // 向右箭头
                Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: () {
                      setState(() {
                        _selectedDate = _selectedDate.add(const Duration(days: 1));
                        _initDayTasks(_selectedDate);
                      });
                    },
                    child: Container(
                      padding: const EdgeInsets.all(12.0),
                      child: const Icon(
                        Icons.chevron_right,
                        size: 40,
                        color: Colors.blue,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                // 左侧统计按钮
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(right: 8.0),
                    child: SizedBox(
                      height: 50,
                      child: ElevatedButton(
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => StatisticsPage(
                                dailyTasks: _dailyTasks,
                                taskTitles: _taskTitles,
                              ),
                            ),
                          );
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Theme.of(context).colorScheme.primary,
                          foregroundColor: Colors.white,
                        ),
                        child: const Text(
                          '任务统计',
                          style: TextStyle(fontSize: 18),
                        ),
                      ),
                    ),
                  ),
                ),
                // 右侧专项统计按钮
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(left: 8.0),
                    child: SizedBox(
                      height: 50,
                      child: ElevatedButton(
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => SpecialStatisticsPage(
                                dailyTasks: _dailyTasks,
                                taskTitles: _taskTitles,
                              ),
                            ),
                          );
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Theme.of(context).colorScheme.primary,
                          foregroundColor: Colors.white,
                        ),
                        child: const Text(
                          '专项统计',
                          style: TextStyle(fontSize: 18),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class Todo {
  String title;
  bool isCompleted;

  Todo({
    required this.title,
    required this.isCompleted,
  });
}
